package com.ztesoft.book.admin.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ztesoft.book.common.constant.Constant;
import com.ztesoft.book.common.utils.base.SnowFlakeGenerator;
import com.ztesoft.book.common.utils.jwt.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Description Mybatis Plus 自动填充Handler
 * @Author YangFan
 * @Date 2021-06-24 10:22
 */
@Slf4j
@Component
public class MpMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取当前登录用户ID
        String token = "";
        try {
            if (ObjectUtil.isNotNull(SecurityUtils.getSubject()) && SecurityUtils.getSubject().getPrincipal() != null) {
                token = SecurityUtils.getSubject().getPrincipal().toString();
            }
        }
        catch (Exception e) {
            log.info("定时器或其他无ThreadContext情况时跳过获取Subject");
        }
        if (ObjectUtil.isNull(this.getFieldValByName("id", metaObject)) || StrUtil.isEmpty(this.getFieldValByName("id", metaObject).toString())) {
            this.setFieldValByName("id", SnowFlakeGenerator.generateIdStr(), metaObject);
        }
        // 如遇到特殊情况下无法获取当前登录人
        String userid = null;
        if (StringUtils.isNotBlank(token)) {
            userid = JwtUtil.getClaim(token, Constant.USERID);
        }
        this.setFieldValByName("createBy", userid, metaObject);
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateBy", userid, metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 获取当前登录用户ID
        String token = "";
        try {
            if (ObjectUtil.isNotNull(SecurityUtils.getSubject()) && SecurityUtils.getSubject().getPrincipal() != null) {
                token = SecurityUtils.getSubject().getPrincipal().toString();
            }
        }
        catch (Exception e) {
            log.info("定时器或其他无ThreadContext情况时跳过获取Subject");
        }
        // 如遇到特殊情况下无法获取当前登录人
        String userid = null;
        if (StringUtils.isNotBlank(token)) {
            userid = JwtUtil.getClaim(token, Constant.USERID);
        }
        this.setFieldValByName("updateBy", userid, metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }
}
